package com.jyh.fillter;


import com.alibaba.fastjson.JSON;
import com.jyh.common.PublicField;
import com.jyh.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //匹配器，支持通配符匹配
    private  static final AntPathMatcher ANT_PATH_MATCHER=new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest httpServletRequest=(HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse=(HttpServletResponse) servletResponse;

        String requestURI = httpServletRequest.getRequestURI();

        //需要放行的urls数组,静态资源全部放行，只是
        String []urls={
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };
        //使用匹配器看url是否符合规则,true放行
        boolean check = check(urls, requestURI);
        if(check){
            //log.info("本次请求{}不需要拦截",requestURI);
            //放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //后端已经登录则直接放行
        if (httpServletRequest.getSession().getAttribute("employee")!=null){
            //log.info("用户已经登录");

            //设置自动填充创建人、更新人
            Long employeeId = (Long) httpServletRequest.getSession().getAttribute("employee");
            PublicField.setCurrentId(employeeId);

            //放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //前台已经登录则直接放行
        Long userId = (Long) httpServletRequest.getSession().getAttribute("user");
        if (userId !=null){
            //log.info("用户已经登录");
            //   通过ThreadLocal set和get用户id
            PublicField.setCurrentId(userId);
            //放行
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }

        //log.info("用户没登录");

        //上述不满足，则过滤后结合前端request.js返回数据
        httpServletResponse.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

    }

    //判断请求的路径是否与放行数组urls匹配，成功返回true，说明匹配上了
    public boolean check(String []urls,String requestURI){
        for (String url :urls ) {
            boolean match = ANT_PATH_MATCHER.match(url, requestURI);
            if(match){
                return true;
            }
        }
        return false;
    }
}
